package com.beiming.libra.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.beiming.libra.common.Assert;
import com.beiming.libra.common.constants.LibraConst;
import com.beiming.libra.common.constants.ValidateMessage;
import com.beiming.libra.common.enums.ErrorCode;
import com.beiming.libra.common.enums.StatusEnum;
import com.beiming.libra.dao.UserMapper;
import com.beiming.libra.dao.UserRoleRelationMapper;
import com.beiming.libra.domain.Role;
import com.beiming.libra.domain.User;
import com.beiming.libra.domain.UserRoleRelation;
import com.beiming.libra.domain.dto.requestdto.UserRoleRelationRequestDTO;
import com.beiming.libra.service.UserRoleRelationService;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

/***
 * 
 * @author weibo
 */
@Service
@Slf4j
public class UserRoleRelationServiceImpl implements UserRoleRelationService {
  @Resource
  private UserRoleRelationMapper userRoleRelationMapper;
  @Resource
  private UserMapper userMapper;

  @Override
  @Transactional
  public void insertUserRoleRelation(UserRoleRelationRequestDTO userRoleRelationRequestDTO) {
    String userId = userRoleRelationRequestDTO.getUserId();
    Assert.isNotNull(userId, ErrorCode.USER_NOT_EXISTS, ValidateMessage.ID_NOT_BLANK);
    User user = userMapper.selectByPrimaryKey(userId);
    Assert.isNotNull(user, ErrorCode.USER_NOT_EXISTS, ValidateMessage.ID_NOT_EXISTS);
    if (StringUtils.isEmpty(userRoleRelationRequestDTO.getRoleIdList())) {
      // 清除所有的权限权限关系
      deleteUserRoleRelation(userRoleRelationRequestDTO);
      return;
    }
    // 新的用户和角色id
    String[] roleId = userRoleRelationRequestDTO.getRoleIdList().split(",");
    // 查询数据库已经存在的角色和权限对应关系
    UserRoleRelation selectObj = new UserRoleRelation();
    selectObj.setUserId(userId);
    selectObj.setStatus(StatusEnum.USED.getCode());
    List<UserRoleRelation> oldList = userRoleRelationMapper.select(selectObj);

    // 保存需要新增的集合
    List<UserRoleRelation> addList = new ArrayList<UserRoleRelation>();
    // 删除需要删除的集合
    List<UserRoleRelation> deleteList = new ArrayList<UserRoleRelation>();
    // 新的用户和角色关系
    List<UserRoleRelation> newList = new ArrayList<UserRoleRelation>();
    for (int i = 0; i < roleId.length; i++) {
      String roleIdStr = roleId[i];
      UserRoleRelation userRoleRelation = null;
      for (UserRoleRelation userRole : oldList) {
        if (userRole.getRoleId().equals(roleIdStr)) {
          userRoleRelation = userRole;
          break;
        }
      }
      if (userRoleRelation == null) {
        userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(userId);
        userRoleRelation.setRoleId(roleIdStr);
        userRoleRelation.setCreateUser(userRoleRelationRequestDTO.getCreateUser());
        userRoleRelation.setCreateTime(new Date());
        userRoleRelation.setUpdateUser(userRoleRelationRequestDTO.getUpdateUser());
        userRoleRelation.setCreateTime(new Date());
        userRoleRelation.setStatus(StatusEnum.USED.getCode());
        userRoleRelation.setRemark(userRoleRelationRequestDTO.getRemark());
        userRoleRelation.setVersion(LibraConst.DEFAULT_VERSION);
        addList.add(userRoleRelation);
      }
      newList.add(userRoleRelation);
    }

    for (UserRoleRelation userRole : oldList) {
      boolean bol = false;
      for (UserRoleRelation authRoleRelation : newList) {
        if (authRoleRelation.getRoleId().equals(userRole.getRoleId())) {
          bol = true;
          break;
        }
      }
      if (!bol) {
        deleteList.add(userRole);
      }
    }
    // 插入
    if (addList.size() > 0) {
      userRoleRelationMapper.insertList(addList);
    }
    if (deleteList.size() > 0) {
      List<String> deleIdList = new ArrayList<String>();
      for (UserRoleRelation userRoleRelation : deleteList) {
        deleIdList.add(userRoleRelation.getId());
      }
      Example deleteExample = new Example(UserRoleRelation.class, false);
      deleteExample.createCriteria().andIn("id", deleIdList);
      // 删除
      userRoleRelationMapper.deleteByExample(deleteExample);
    }
  }

  @Override
  public List<UserRoleRelation> getUserRoleRelation(UserRoleRelationRequestDTO userRoleRelationRequestDTO) {
    String userId = userRoleRelationRequestDTO.getUserId();
    Assert.isNotNull(userId, ErrorCode.USER_NOT_EXISTS, ValidateMessage.ID_NOT_BLANK);
    UserRoleRelation userRoleRelation = new UserRoleRelation();
    userRoleRelation.setId(userRoleRelationRequestDTO.getId());
    userRoleRelation.setUserId(userRoleRelationRequestDTO.getUserId());
    userRoleRelation.setStatus(StatusEnum.USED.getCode());
    return userRoleRelationMapper.select(userRoleRelation);
  }

  @Override
  public void deleteUserRoleRelation(UserRoleRelationRequestDTO userRoleRelationRequestDTO) {
    String userId = userRoleRelationRequestDTO.getUserId();
    Assert.isNotNull(userId, ErrorCode.USER_NOT_EXISTS, ValidateMessage.ID_NOT_BLANK);
    if (userRoleRelationRequestDTO.getUpdateTime() == null) {
      userRoleRelationRequestDTO.setUpdateTime(new Date());
    }
    Example example = new Example(UserRoleRelation.class, false);
    example.createCriteria().andEqualTo("userId", userId);
    userRoleRelationMapper.deleteByExample(example);
  }

  @Override
  public List<Role> getRoleInfoByUserId(String userId) {
    Assert.isNotNull(userId, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.ID_NOT_BLANK);
    return userRoleRelationMapper.getRoleInfoByUserIdMapper(userId);
  }

}
